local gPlayerTickCount = { }
local gPlayerSpams = { }
local gPlayerMessage = { }
local gPlayerMsgNum = { }
local gPlayerMuteTimer = { }

local gSettings = { }

addEventHandler( "onPlayerChat", getRootElement( ),
    function( message )
        if not gPlayerSpams[ source ] then
			gPlayerSpams[ source ] = true
			gPlayerTickCount[ source ] = getTickCount( )
            gPlayerMessage[ source ] = message
        else
			if getTickCount( ) - gPlayerTickCount[ source ] > gSettings.delay then
				gPlayerMsgNum[ source ] = 0
				gPlayerMessage[ source ] = nil;
				gPlayerTickCount[ source ] = getTickCount( )
				return
			else
				if gPlayerMsgNum[ source ] >= gSettings.msgNum then
					gPlayerTickCount[ source ] = getTickCount( )
					cancelEvent( )
					if gSettings.mutePlayers then
						mutePlayer( source );
					end
				elseif message == gPlayerMessage[ source ] then
					cancelEvent( )
				end
				gPlayerMsgNum[ source ] = gPlayerMsgNum[ source ] + 1
			end
        end
		gPlayerMessage[ source ] = message
    end
)

function mutePlayer( player )
	local data = getElementData(player,"player:data")
	data.mute = true
	setElementData(player,"player:data",data)
	setPlayerMuted( player, true );
	gPlayerMuteTimer[ player ] = setTimer( unmutePlayer, gSettings.muteTime * 1000, 1, player );
	exports['cmta-notyfikacje']:sendNotification(player,"#FF0000Anty-Spam\n#ffffffZostałeś wyciszony na " .. gSettings.muteTime .." s.","error",6000)
end

function unmutePlayer( player )
	local data = getElementData(player,"player:data")
    data.mute = false
	setElementData(player,"player:data",data)
	setPlayerMuted( player, false );
	exports['cmta-notyfikacje']:sendNotification(player,"#ccc000Anty-Spam\n#ffffffCzas wyciszenia minął.","info",4000)

end

addEventHandler( "onPlayerJoin", getRootElement( ),
	function( )
		gPlayerMsgNum[ source ] = 0
	end
)

addEventHandler( "onResourceStart", getResourceRootElement( getThisResource() ),
    function( )
        gSettings.delay = get( "@differenceBetweenMessages_ms" )
		gSettings.msgNum = get( "@messagesNumber" )
		gSettings.mutePlayers = ( get( "@mutePlayers" ) == "true" ) and true or false;
		gSettings.muteTime = get( "@muteTime" );
		for _, plr in pairs( getElementsByType( "player" ) ) do
			gPlayerMsgNum[ plr ] = 0
		end
    end
)

addEventHandler( "onResourceStop", getResourceRootElement(),
	function( )
		local players = getElementsByType( "player" );
		for i, plr in pairs( players ) do
			if isPlayerMuted( plr ) then
				setPlayerMuted( plr, false );
			end
		end
	end
)